<template>
  <div class="com-container">
    <div class="com-chart" ref="seller_ref"></div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUnmounted, nextTick } from "vue";
import { getThemeValue } from "@/utils/theme_utils.ts";
import { useThemeChart } from "@/hooks/useThemeChart.ts";

const { proxy } = getCurrentInstance()!;
const seller_ref = ref();
const allData = ref([]);
const echartsInstance = ref(null);
const currentPage = ref(1);
const totalPage = ref(0);
const timerId = ref(null);

// 初始化echartsInstance对象
const initChart = () => {
  echartsInstance.value = proxy!.$echarts.init(seller_ref.value, themeStore.theme);
  // 对图表初始化配置的控制
  const initOption = {
    title: {
      text: "▎商家销售统计",
      left: 20,
      top: 20
    },
    backgroundColor: getThemeValue(themeStore.theme).bgColor,
    grid: {
      top: "20%",
      left: "3%",
      right: "6%",
      bottom: "3%",
      containLabel: true // 距离是包含坐标轴上的文字
    },
    xAxis: {
      type: "value"
    },
    yAxis: {
      type: "category"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line",
        z: 0,
        lineStyle: {
          type: "solid",
          color: "#2D3443"
        }
      }
    },
    series: [
      {
        type: "bar",
        label: {
          show: true,
          position: "right",
          color: getThemeValue(themeStore.theme).labelColor
        },
        itemStyle: {
          // 指明颜色渐变的方向
          // 指明不同百分比之下颜色的值
          color: new proxy!.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
            // 百分之0状态之下的颜色值
            {
              offset: 0,
              color: "#5052EE"
            },
            // 百分之100状态之下的颜色值
            {
              offset: 1,
              color: "#AB6EE5"
            }
          ])
        }
      }
    ]
  };
  echartsInstance.value.setOption(initOption);
  // 对图表对象进行鼠标事件的监听
  echartsInstance.value.on("mouseover", () => {
    clearInterval(timerId.value);
  });
  echartsInstance.value.on("mouseout", () => {
    startInterval();
  });
};

// 获取服务器的数据
const getData = async res => {
  allData.value = res;
  // 对数据排序
  allData.value.sort((a, b) => {
    return a.value - b.value; // 从小到大的排序
  });
  // 每5个元素显示一页
  totalPage.value = Math.ceil(allData.value.length / 5);
  updateChart();
  // 启动定时器
  startInterval();
};

// 更新图表
const updateChart = () => {
  const start = (currentPage.value - 1) * 5;
  const end = currentPage.value * 5;
  const showData = allData.value.slice(start, end);
  const sellerNames = showData.map(item => {
    return item.name;
  });
  const sellerValues = showData.map(item => {
    return item.value;
  });
  const dataOption = {
    yAxis: {
      data: sellerNames
    },
    series: [
      {
        data: sellerValues
      }
    ]
  };
  echartsInstance.value.setOption(dataOption);
};

const startInterval = () => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  timerId.value = window.setInterval(() => {
    currentPage.value++;
    if (currentPage.value > totalPage.value) {
      currentPage.value = 1;
    }
    updateChart();
  }, 3000);
};

const screenAdapter = () => {
  const titleFontSize = (seller_ref.value.offsetWidth / 100) * 3.6;
  // 和分辨率大小相关的配置项(适配文字标题的大小)
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize
      }
    },
    tooltip: {
      axisPointer: {
        lineStyle: {
          width: titleFontSize
        }
      }
    },
    series: [
      {
        barWidth: titleFontSize,
        itemStyle: {
          borderRadius: [0, titleFontSize / 2, titleFontSize / 2, 0] // 设置圆角的大小
        }
      }
    ]
  };
  echartsInstance.value.setOption(adapterOption);
  // 手动的调用图表对象的resize 才能产生效果
  echartsInstance.value.resize();
};

const { themeStore } = useThemeChart(echartsInstance, initChart, updateChart);

onMounted(async () => {
  try {
    proxy.$socket.registerCallBack("sellerData", getData);
    await nextTick();
    initChart();
    proxy.$socket.send({
      action: "getData",
      socketType: "sellerData",
      chartName: "seller",
      value: ""
    });
    window.addEventListener("resize", screenAdapter);
  } catch (error) {
    console.error("Mounted hook error:", error);
  }
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  // 在组件销毁的时候, 需要将监听器取消掉
  window.removeEventListener("resize", screenAdapter);
  // 注销回调（使用可选链操作符）
  proxy.$socket.unRegisterCallBack("sellerData");
});

defineExpose({
  screenAdapter
});
</script>
